<template>
  <div class="main">

    <mt-header v-show="tab!='r'" fixed :title="tittle[tab]">
      <mt-button>
        <img src="../assets/settings.png" slot="icon" >
      </mt-button>
    </mt-header>
    <mt-tab-container  :value="`tab-${tab}`" >
      <mt-tab-container-item id="tab-s">
        <div class="container search">
          <input class="book" v-model="query"  :class="{mt:results.length==0}" placeholder="输入书名搜索">
          <ul class="results">
            <li  v-for="item in results" >
              <h3 class="book-name" @click="getBook(item.link)">{{item.title}}</h3>
              <p v-for="info in item.all" v-text="info"></p>
              <p v-if="item.desc">简介：{{item.desc}}</p>
            </li>
          </ul>

        </div>
      </mt-tab-container-item>
      <mt-tab-container-item id="tab-b">
        <div class="container">
          <h3 align="center" v-text="book.title"></h3>
          <div class="info" v-if="book.title">
            <p  v-for="info in infos" v-text="info"></p>
            <p>简介：{{book.desc}}</p>
          </div>
          <mt-cell
            v-for="item in book.chapters"
            :title="item.name"
            :to="'/read?url='+item.url"
            :key="item.name"
            is-link
          >
          </mt-cell>
          <mt-button class="btn-center"  @click="catalog = true" v-if="book.title">目录</mt-button>
          <p class="none" v-else>暂无数据</p>
        </div>
      </mt-tab-container-item>
      <mt-tab-container-item id="tab-r">
        <div class="read" id="read" >
          <chapters v-if="chapter.title" @tobook="toBook" @hideTab="hideTab" @loadNext="loadNext" :chapter="chapter"></chapters>
          <p class="none" v-else>暂无数据</p>
        </div>
      </mt-tab-container-item>
      <mt-tab-container-item id="tab-c">
        <div class="collects"  >
          <h4 align="left">上次阅读</h4>
          <p class="collect" v-for="collect in collects">
            {{collect.novel.name}}
          </p>
        </div>
      </mt-tab-container-item>
    </mt-tab-container>
    <tabBar  :showTab="showTab"></tabBar>
    <mt-popup
      v-model="catalog"
      position="bottom">
      <div  class="popup-scroll">
        <mt-cell  v-for="item in book.pages"
                  :title="item.name"
                  :to="'/read?page='+item.url"
                  :key="item.name"
                  is-link></mt-cell>
      </div>
    </mt-popup>
  </div>
</template>

<script>
  import axios from 'axios';
  import { mapGetters } from 'vuex';
  import Chapters  from './Chapters.vue';
  import TabBar from '@/components/TabBar'
  import { Indicator } from 'mint-ui';
  import Cookies from 'js-cookie';
  export default {
    metaInfo: {
      // if no subcomponents specify a metaInfo.title, this title will be used
      title: '阅读器',
      // all titles will be injected into this template
      titleTemplate: '%s | 小说阅读'
    },
    components:{
      chapters:Chapters,
      tabBar:TabBar,
    },
    data(){
      return {
        results:[],
        collects:[],
        infos:[],
        cached:[],
        catalog:false,
        showTab:true,
        login:false,
        book:{chapters:[],pages:[],author:''},
        query:'',
        booklink:'',
        tittle:{
          s:'搜索',
          b:'书籍',
          r:'阅读',
          c:'个人中心'
        },
        chapter:{},
        empty:{
          title:'查无结果',
          all:[],
        },
        totalCached:5,
        cacheUrl:''
      }
    },
    beforeRouteUpdate (to, from, next) {
      if(to.query.url){
        this.getChapter(to.query.url)
        next()
      }
      if(to.query.page){
        this.getBook(to.query.page)
      }

    },
    created(){
      let index = location.host.indexOf('gakki')>=0?1:0;
      this.$store.dispatch('switchUrl',index);
      if(this.$route.query.url){
        this.getChapter(this.$route.query.url)
      }
    },
    watch:{
      cacheUrl(nv){
        if(nv&&this.totalCached>0){
          axios.get(`${this.url}api/novel?curl=${nv}`).then(res=>{
            const next = res.data;
            next.url = nv;
            this.cacheUrl = res.data.next;
            this.totalCached --;
            this.cached.push(next)
          })
        }
        if(this.totalCached === 0){
          this.totalCached = 5
        }
      },
      query(nv){
        if(this.query!=''){
          this.getList()
        }else {
          this.results = [];
        }
      }
    },
    computed: {
      ...mapGetters([
        'url',
        'tab'
      ])
    },
    methods:{
      setTab(tab){
        this.$store.dispatch('switchTab',tab)
      },
      toBook(){
        this.setTab('b');
        if(!this.showTab){
          this.showTab = true;
        }
      },
      hideTab(){
        this.showTab = !this.showTab;
      },
      loadNext(next){
        let url = this.chapter.next;
        if(!next) {
          url = this.chapter.prev;
        }
        if(url!=this.booklink){
          this.$router.push('/read?url='+url)
        }
      },
      getChapter(url){
        let chapterCached = this.cached.find(e=>e.url==url);
        if(chapterCached){
          this.chapter = chapterCached;
          this.loadChapter();
        }else {
          axios.get(`${this.url}api/novel?curl=${url}`).then(res=>{
            this.chapter = res.data;
            this.cacheUrl = res.data.next;
            this.cached = [];
            this.loadChapter();
          })
        }
      },
      loadChapter(){
        if(this.chapter.title){
          Cookies.set('title',Cookies.get('bookTitle') + '\t'+ this.chapter.title)
          this.setTab('r');
          this.$nextTick(()=>{
            window.scrollTo(0,0)
          })
        }
      },
      getBook(url){
        if(url.indexOf('index')<0){
          this.booklink = url;
        }
        axios.get(`${this.url}api/novel?url=${url}`).then(res=>{
          this.book = res.data;
          if(this.book.title){
            Cookies.set('bookTitle',this.book.title, { expires: 365 });
            this.setTab('b');
            this.catalog = false;
            this.infos = this.book.author.replace(/\n/g,',').replace(/\s/g,'').split(',');
            this.infos.shift();
          }
        })
      },
      getList(){
        if(this.query.trim()==='')
          return
        Indicator.open();
        axios.get(`${this.url}api/novels?q=${this.query}`).then(res=>{
          let data  = res.data;
          this.results =[];
          if(data.code === 200 && this.query !== ''){
            data.list.forEach(item =>{
              item.forEach(i=>{
                i.link=i.link.replace('http://m.biduo.cc','')
                this.results.push(i);
              })
            })
            if(this.results.length == 0){
              this.results.push(this.empty)
            }
          }else{
            this.results=[this.empty]
          }
          Indicator.close();
        }).catch(err =>{
          Indicator.close();
        })
      }
    }
  }
</script>

<style scoped>
  .info{
    padding: 10px 10px;
    border-bottom: 1px solid;
    line-height: 1.4em;
  }
  p{
    margin: 0;
  }
  .popup-scroll{
    width: 100vw;
    overflow-scrolling: touch;
    -webkit-overflow-scrolling:touch;
    overflow-y: scroll;
    max-height: 50vh;
  }
  .popup-scroll p{
    border-bottom: 1px solid #bfbfbf;
    padding: 5px 0;
    text-align: left;
    text-indent: 1em;
  }
  .none{
    text-align: center;
    font-size: 1.2em;
    margin-top: 20vh;
  }

  .mt{
    margin-top: 40vh;
  }
  .container{
    text-align: left;
    padding: 45px 0 55px;
    min-height: calc(100vh - 100px);
    overflow-y: scroll;
  }
  .search{
    text-align: center;
    background: #4e81cf;
  }
  .results{
    list-style: none;
    color: #fff;
    text-align: left;
    margin: 0;
    padding: 0;
  }
  .btn-center{
    margin: 0 auto 10px;
    display: block;
  }
  .results li{
    border-bottom: 1px solid #fff;
    padding: 10px 20px;
  }
  .book{
    border-radius: 5px;
    border: 1px solid #fff;
    outline: none;
    text-indent: 0.5em;
    line-height: 2em;
    font-size: 1.1em;
    width: 80vw;
    transition: all 1s;
  }
</style>
